package com.youlu.campus.web.linker;

import com.youlu.campus.common.exception.BusinessException;

import com.youlu.campus.entity.HuoLinkerInfo;
import com.youlu.campus.service.linker.HuoLinkerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Controller
public class HuoLinkerInfoController {
    @Autowired
    private HuoLinkerInfoService huoLinkerInfoService;


    @RequestMapping("/public/short-url/{shortUrl}")
    public void shortUrl(@PathVariable("shortUrl") String shortUrl, HttpServletResponse response) {
        HuoLinkerInfo linkerInfo = huoLinkerInfoService.find(shortUrl);
        if (Objects.isNull(linkerInfo)) {
            log.error(":>>> 短链接不存在:{}", shortUrl);
            throw new BusinessException("非法请求");
        }
        log.info(":>>> 短链接:{} 生成的长链接地址为:{}", shortUrl, linkerInfo.getUrl());
        try {
            response.sendRedirect(linkerInfo.getUrl());
        } catch (Exception e) {
            log.error(":>>> 短链接地址错误:{}", e);

        }

    }
}
